package com.redstar.HappyRefresh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redstar.HappyRefresh.mapper.FavoritesVideoMapper;
import com.redstar.HappyRefresh.pojo.FavoritesVideo;
import com.redstar.HappyRefresh.service.FavoritesVideoService;
import org.springframework.stereotype.Service;

@Service
public class FavoritesVideoServiceImpl extends ServiceImpl<FavoritesVideoMapper, FavoritesVideo> implements FavoritesVideoService {

    @Override
    public Boolean favoritesState(Long videoId, Long userId) { // userId是否收藏videoId
        if (userId == null) { // 游客登录
            return false;
        }
        long count = count(new LambdaQueryWrapper<FavoritesVideo>().eq(FavoritesVideo::getVideoId, videoId).eq(FavoritesVideo::getUserId, userId));
        return count == 1;
    }

    @Override
    public Boolean favoritesVideo(FavoritesVideo favoritesVideo) { // 收藏视频/取消收藏
        try {
            // favorites_id，video_id，user_id为favorites_video表的唯一索引，重复插入会抛出异常
            save(favoritesVideo);
        } catch (Exception e) { // 取消收藏
            Long favoritesId = favoritesVideo.getFavoritesId();
            Long videoId = favoritesVideo.getVideoId();
            Long userId = favoritesVideo.getUserId();
            remove(new LambdaQueryWrapper<FavoritesVideo>()
                    .eq(FavoritesVideo::getFavoritesId, favoritesId)
                    .eq(FavoritesVideo::getVideoId, videoId)
                    .eq(FavoritesVideo::getUserId, userId));
            return false;
        }
        return true;
    }
}
